<template>
	<view class="mx30 py20">
		<view class="mb20" v-if="navList.length">
			<u-subsection :list="navList" :current="currentVal" active-color="#2979ff" @change="change"></u-subsection>
		</view>
		<view v-if="current === 0 && is_house ==1">
			<u-tabs :list="tabList" :is-scroll="false" :current="tabsCurrent" @change="changeTab"></u-tabs>
		</view>
		<div>
			<u-empty mode="list" margin-top="80" v-if="list.length === 0"></u-empty>

			<template v-if="current === 1">
				<div class="mb30 bg-fff p20 radius16" v-for="item in list" :key="item.id" @click="showPopup(item)">
					<view class="flex row-between">
						<text>{{ item.order_sn }}</text>
						<text> {{ item.status_text }}</text>
					</view>
					<view class="flex row-between border-b py20">
						<view class="flex ">
							<image class="w120 h120 radius10" :src="item.pic" mode="scaleToFill" />
							<text class="text ml20 fs34" v-if="locale == 'cn' || locale == 'zh-Hans'">{{ item.title }}</text>
							<text class="text ml20 fs34" v-if="locale == 'ey'">{{ item.wei_title }}</text>
							<text class="text ml20 fs34" v-if="locale == 'kk'">{{ item.ha_title }}</text>
						</view>

						<!-- <view class="theme-price">预约金:{{ item.money }}</view> -->
					</view>

					<div class="flex row-between pt20">
						<view class="flex ">
							<view class="mr10 w100">发布人:</view>
							<image class="w40 h40 radius" :src="item.uinfo.avatar" mode="scaleToFill" />
							<text class="ml10 truncate-1 ml30">{{ item.uinfo.name }}</text>
						</view>
						<text class="fs24 color-999"> {{ item.uinfo.mobile }}</text>
					</div>
				</div>
			</template>

			<template v-else>
				<div class="list2">
					<div class="item " v-for="item in list" :key="item.id">
						<div class="top">
							<div class="left">
								<u-avatar size="92" :src="item.avatar"></u-avatar>
								<div class="info">
									<div class="top">
										
										<div class="name">{{ item.name }}</div>
										<div class="title">{{ item.type_name }}</div>
									</div>
									<div class="phone">{{ item.mobile }}</div>
								</div>
							</div>
							<div class="contact" @click="currenId = item.id, showModal = true
                                ">
								接单
							</div>
						</div>
						<div class="bottom">{{ item.sale_time }}</div>
					</div>

				</div>
			</template>
		</div>

		<u-loadmore :status="status" v-if="list.length > params.page_size" />
		<u-popup v-model="show" mode="center" width="90%" border-radius="16">
			<view class="popup">
				<view class="title">接单信息</view>

				<view class="item">
					服务类型: {{ currentItem.title }}
				</view>
				<!-- <view class="item">
                    接单金额:{{ currentItem.service_finish_amount }}
                </view> -->
				<view class="item ">
					发布人:{{ currentItem.uinfo.name }}
				</view>
				<view class="item">
					发布时间:{{ currentItem.pay_time }}
				</view>
				
				<view class="item ">
					姓名:{{ currentItem.name }}
				</view>
				
				<view class="item ">
					手机号:{{ currentItem.phone }}
				</view>
				
				<view class="item ">
					地址:{{ currentItem.address_name }}
				</view>
				<view class="item">
					备注:{{ currentItem.remark }}
				</view>

				<view style="margin:30rpx">
					<u-button type="primary" @click="submit">接单</u-button>
				</view>
			</view>
		</u-popup>

		<u-modal v-model="showModal" content="接单后请及时联系客户" show-cancel-button @confirm="confirmModal"></u-modal>
	</view>
</template>

<script>
	import permision from "@/js_sdk/wa-permission/permission.js"

	export default {
		data() {
			return {
				showModal: false,
				status: 'loadmore',
				remark: '',
				show: false,
				current: 0,
				tabsCurrent: 0,
				list: [],
				currentItem: {
					uinfo: {}
				},
				params: {
					id: '',
					page: 1,
					page_size: 10,
					type: 1
				},
				last_page: '',
				tabList: [{
					name: '二手房'
				}, {
					name: '新房'
				}, {
					name: '租房',
				}],
				currenId: "",
				is_house: "",
				is_service: "",
				currentNav: 0,
				currentVal: 0,
				locale: 'cn',
				// 记录的时间
				locationTime: 0,
			}
		},
		onLoad() {
			this.is_house = uni.getStorageSync('is_house');
			this.is_service = uni.getStorageSync('is_service');
			if (this.is_service == 1 && this.is_house == 0) {
				this.current = 1
			}
			if (this.current == 0) {
				this.get_house_list()
			} else {
				this.get_service_cate()
			}

			uni.getStorage({
				key: 'locale',
				success: (res) => {
					this.locale = res.data
				}
			})
		},
		onShow() {
			this.websocketDispose()
			
			this.getUserInfo()
			// #ifdef APP-PLUS
			this.checkOpenService().then(() => {
				this.checkOpenPermission().then(() => {
					this.locationChange()
				}).catch(() => {
					uni.showModal({
						content: '请开启位置信息权限',
						showCancel: false,
						success() {
							permision.gotoAppPermissionSetting()
						}
					})
				})
			})
			// #endif
			// #ifndef APP-PLUS
			this.locationChange()
			// #endif
			// 监听持续定位接口返回失败时触发
			uni.onLocationChangeError((err) => {
				console.log('onLocationChangeError', err);
			})
			// 取消注册位置更新错误回调
			uni.offLocationChangeError((err) => {
				console.log('offLocationChangeError', err);
			})
		},
		computed: {
			navList() {
				let nav = []
				if (this.is_house == 1) {
					nav.push({
						name: '房产大厅'
					})
				}
				if (this.is_service == 1) {
					nav.push({
						name: '家政大厅'
					})
				}
				return nav
			}
		},
		methods: {
			confirmModal() {
				this.$u.api.seize_orders({
					id: this.currenId
				}).then(res => {
					this.$u.toast(res.msg)
					this.params.page = 1
					this.list = []
					this.currenId = ''
					this.get_house_list()
				})
			},
			websocketDispose() {
				// 刷新订单数据
				uni.$off('orderType')
				uni.$on("orderType", (res) => {
					this.params.page = 1
					this.list = []
					if (this.current === 1) {
						this.get_service_cate()
					} else {
						this.get_house_list()
					}
				})
				uni.$off('bind_client_id')
				uni.$on("bind_client_id", (client_id) => {
					console.log('client_id', client_id)
					this.bind_client_id(client_id)
				})
			},
			bind_client_id(client_id) {
				uni.$u.api.bind_uid({
					client_id
				}).then(res => {
					console.log('res: ', res);
				})
			},
			changeTab(index) {
				this.tabsCurrent = index
				this.params.page = 1
				this.params.type = index + 1
				this.list = []
				this.get_house_list()
			},
			change(index) {
				console.log('index: ', index);
				this.currentNav = index
				this.currentVal = index
				console.log('index: ', index);
				this.params.page = 1
				this.current = index;
				this.list = []
				if (index === 0) {
					this.get_house_list()
				} else {
					this.get_service_cate()
				}

			},
			get_service_cate() {
				this.$u.api.order_hall().then(res => {
					this.last_page = res.data.last_page
					this.list = [...this.list, ...res.data.data, ]
				})
			},
			get_house_list() {
				this.status = 'loading'
				this.$u.api.house_hall(this.params).then(res => {
					this.last_page = res.data.total_page
					this.list = [...this.list, ...res.data.data];
				});
			},
			showPopup(item) {
				this.show = true
				this.currentItem = item
				this.params.id = item.id
			},
			submit() {
				this.show = false
				this.$u.api.receive_order(this.params).then(orderRes => {
					this.$u.toast(orderRes.msg)
					this.list = []
					this.params.page
					this.get_service_cate()
				})
			},
			getUserInfo() {
				this.$u.api.material().then(res => {
					uni.setStorageSync('is_house', res.data.data?.is_house);
					uni.setStorageSync('is_service', res.data.data?.is_service);
					this.getTabbar(res.data.data?.is_house, res.data.data?.is_service);
				});
			},
			// 开始监听位置
			locationChange() {
				uni.startLocationUpdate({
					type: 'gcj02',
					success: () => {
						// 先取消监听位置变化
						uni.offLocationChange(this.offLocationCall)
			
						// 开始监听位置变化
						uni.onLocationChange(this.locationChangeFn)
					},
					fail: (err) => {
						console.log('startLocationUpdateErr', err);
					}
				})
			},
			offLocationCall(){
				console.log("关闭监听位置")
			},
			// 关闭
			offLocationChange() {
				uni.offLocationChange(this.locationChangeFn)
			},
			// 监听实时地理位置变化处理函数
			locationChangeFn(res, type) {
				const currentTime = new Date().getTime()

				// 时间间隔2秒
				if (currentTime - this.locationTime > 10000) {
					this.locationTime = currentTime
					this.updateSalesmanLocation(res.latitude, res.longitude);
				}
			},
			updateSalesmanLocation(latitude, longitude) {
				this.$u.api.salesman_location({
					latitude: latitude,
					longitude: longitude
				}).then(res => {
					 if(res.data.is_have_tip == 1){
						 let playMp3 = '/static/mp3/'+res.data.mp3_url;
						 let innerAudioContext = null
						 innerAudioContext = uni.createInnerAudioContext();
						 innerAudioContext.autoplay = true;
						 innerAudioContext.src = playMp3;
						 innerAudioContext.onCanplay(() => {
							innerAudioContext.play()
						 })
						 innerAudioContext.onPlay(() => {
							 console.log('开始播放');
						 });
						 innerAudioContext.onError((res) => {
							 console.log('res: ', res);
							 // console.log(res.errMsg);
							 // console.log(res.errCode);
						 });
						 innerAudioContext.onEnded((res) => {
							 // console.log('音频自然播放结束')
							 innerAudioContext.destroy()
						 });
					 }
				
				});
			},
			// 检查是否开启位置权限
			checkOpenService () {
				let result = permision.checkSystemEnableLocation()
				
				return new Promise((resolve, reject) => {
					if(!result) {
						uni.showModal({
							content: '请打开定位服务功能',
							showCancel: false,
							success () {
								let main = plus.android.runtimeMainActivity();
								let Intent = plus.android.importClass('android.content.Intent')
								let Settings = plus.android.importClass('android.provider.Settings')
								let intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)
								main.startActivity(intent)
							}
						})
						
						reject()
					} else {
						resolve()
						console.log('已开启定位服务功能')
					}
				})
			},
			// 检查是否开启位置信息权限
			checkOpenPermission () {
				let systemType = uni.getSystemInfoSync().platform
				
				return new Promise((resolve, reject) => {
					if (systemType === 'android') {
						permision.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION').then((result) => {
							if (result == 1) {
								// 已获得授权
								resolve()
							} else {
								// 未获得授权
								reject()
							}
						})
					}
				})
			},
			getTabbar(is_house, is_service) {
				if (is_service === 1 && is_house === 1) {
					uni.setTabBarItem({
						// 修改底部导航
						index: 0,
						visible: true
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 1,
						visible: true
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 2,
						visible: true
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 3,
						visible: true
					});
				}
			
				if (is_service === 1 && is_house === 0) {
					uni.setTabBarItem({
						// 修改底部导航
						index: 3,
						visible: true
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 2,
						visible: true
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 0,
						visible: false
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 1,
						visible: false
					});
				}
			
				if (is_service === 0 && is_house === 1) {
					uni.setTabBarItem({
						// 修改底部导航
						index: 3,
						visible: false
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 2,
						visible: true
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 0,
						visible: true
					});
					uni.setTabBarItem({
						// 修改底部导航
						index: 1,
						visible: true
					});
				}
			},
		},
		onReachBottom() {
			if (this.last_page > this.params.page) {
				this.status = 'loading'
				this.params.page++
				if (this.current === 0) {
					this.get_house_list()
				} else {
					this.get_service_cate()
				}
			} else {
				this.status = 'nomore'
			}
		},
		onPullDownRefresh() {
			setTimeout(() => {
				uni.stopPullDownRefresh()
				uni.reLaunch({
					url: '/pages/orderTaking/index'
				});
			}, 800)
		},
	}
</script>

<style lang="scss" scoped>
	.popup {
		margin: 20rpx;

		.title {
			font-size: 40rpx;
			font-weight: 500;
			text-align: center;
			margin-bottom: 30rpx;
		}

		.item {
			margin-bottom: 30rpx;
			font-size: 34rpx;
		}
	}

	.list2 {
		margin-top: 40rpx;

		.item {

			background: #ffffff;
			padding: 26rpx 20rpx;
			margin-bottom: 30rpx;
			box-shadow: 0rpx 2rpx 3rpx 1rpx rgba(0, 0, 0, 0.07);
			border-radius: 10rpx 10rpx 10rpx 10rpx;

			.top {
				@include flex($justify: space-between, $aligin: center);

				.left {
					@include flex($aligin: center);
				}

				image {
					width: 92rpx;
					height: 92rpx;
				}

				.info {
					margin-left: 20rpx;

					.top {
						@include flex($aligin: center);

						.title {
							color: #ffffff;
							background: linear-gradient(91deg, rgb(112, 189, 254) 1%, rgb(68, 144, 255) 99%);
							padding: 5rpx 10rpx;
							margin-left: 20rpx;
							border-radius: 5rpx
						}
					}

					.name {
						font-size: 29rpx;
						color: #232323;
						width: 200rpx;
					}

					.phone {
						margin-top: 10rpx;
						font-size: 27rpx;
						color: #999999;
					}
				}

				.contact {
					height: 64rpx;
					border-radius: 110rpx;
					padding: 0 30rpx;
					background: #ffc13a;
					color: #ffffff;
					line-height: 64rpx;
				}

			}

			.bottom {
				text-align: right;
				margin-top: 20rpx;
				font-size: 24rpx;
				color: #999999;
			}
		}
	}
</style>

<style>
	page {
		background-color: #f8f8f8;
	}
</style>